import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic
} from 'antd'
import {
  PlusOutlined,
  CloudUploadOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SettingOutlined,
  SyncOutlined,
  SearchOutlined,
  TableOutlined
} from '@ant-design/icons'
import { PageResult, WideTable, WideTableField } from '@/types/index'
import { request } from '@/services/api'
import { useNavigate } from 'react-router-dom'
import type { ColumnsType } from 'antd/es/table'

const { Option } = Select
const { TextArea } = Input

interface WideTableQueryForm {
  name?: string
  displayName?: string
  type?: 'ONLINE' | 'OFFLINE'
  status?: 'ACTIVE' | 'INACTIVE'
  creator?: string
}

interface CreateWideTableForm {
  name: string
  displayName: string
  description?: string
  type: 'ONLINE' | 'OFFLINE'
  dataSource?: string
  esIndexName?: string
  fields: WideTableFieldForm[]
}

interface WideTableFieldForm {
  fieldName: string
  displayName: string
  fieldType: 'STRING' | 'NUMBER' | 'DATE' | 'BOOLEAN'
  fieldLength?: number
  precisionScale?: string
  nullable?: boolean
  defaultValue?: string
  description?: string
  isDisplayField?: boolean
  isQueryField?: boolean
  sortOrder?: number
}

const WideTableManagement: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const [wideTableList, setWideTableList] = useState<WideTable[]>([])
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [queryForm] = Form.useForm<WideTableQueryForm>()
  const [createForm] = Form.useForm<CreateWideTableForm>()
  const [fieldForm] = Form.useForm()
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [fieldModalVisible, setFieldModalVisible] = useState(false)
  const [editingWideTable, setEditingWideTable] = useState<WideTable | null>(null)
  const [statistics, setStatistics] = useState({
    total: 0,
    online: 0,
    offline: 0,
    active: 0
  })

  // 查询数据宽表列表
  const fetchWideTableList = async (params?: any) => {
    setLoading(true)
    try {
      const queryParams = {
        current: pagination.current,
        size: pagination.pageSize,
        ...queryForm.getFieldsValue(),
        ...params
      }

      const response = await request.get<PageResult<WideTable>>('/wide-tables', queryParams)
      setWideTableList(response.data.records)
      setPagination({
        ...pagination,
        total: response.data.total,
        current: response.data.current
      })
    } catch (error) {
      message.error('查询失败')
    } finally {
      setLoading(false)
    }
  }

  // 获取统计信息
  const fetchStatistics = async () => {
    try {
      const response = await request.get('/wide-tables/statistics')
      setStatistics(response.data)
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 创建/更新数据宽表
  const handleCreateOrUpdate = async (values: CreateWideTableForm) => {
    try {
      if (editingWideTable) {
        await request.put(`/wide-tables/${editingWideTable.id}`, values)
        message.success('更新成功')
      } else {
        await request.post('/wide-tables', values)
        message.success('创建成功')
      }
      setCreateModalVisible(false)
      setEditingWideTable(null)
      createForm.resetFields()
      fetchWideTableList()
      fetchStatistics()
    } catch (error) {
      message.error(editingWideTable ? '更新失败' : '创建失败')
    }
  }

  // 删除数据宽表
  const handleDelete = async (id: number) => {
    try {
      await request.delete(`/wide-tables/${id}`)
      message.success('删除成功')
      fetchWideTableList()
      fetchStatistics()
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 更新状态
  const handleStatusChange = async (id: number, status: 'ACTIVE' | 'INACTIVE') => {
    try {
      await request.put(`/wide-tables/${id}/status?status=${status}`)
      message.success('状态更新成功')
      fetchWideTableList()
      fetchStatistics()
    } catch (error) {
      message.error('状态更新失败')
    }
  }

  // 同步到Elasticsearch
  const handleSync = async (id: number) => {
    try {
      await request.post(`/wide-tables/${id}/sync`)
      message.success('同步成功')
    } catch (error) {
      message.error('同步失败')
    }
  }

  // 编辑数据宽表
  const handleEdit = (record: WideTable) => {
    setEditingWideTable(record)
    createForm.setFieldsValue({
      name: record.name,
      displayName: record.displayName,
      description: record.description,
      type: record.type,
      dataSource: record.dataSource,
      esIndexName: record.esIndexName
    })
    setCreateModalVisible(true)
  }

  // 管理字段
  const handleManageFields = async (record: WideTable) => {
    try {
      const response = await request.get<WideTableField[]>(`/wide-tables/${record.id}/fields`)
      fieldForm.setFieldsValue({ fields: response.data })
      setEditingWideTable(record)
      setFieldModalVisible(true)
    } catch (error) {
      message.error('获取字段信息失败')
    }
  }

  // 保存字段配置
  const handleSaveFields = async (values: { fields: WideTableFieldForm[] }) => {
    try {
      await request.put(`/wide-tables/${editingWideTable?.id}/fields`, values.fields)
      message.success('字段配置保存成功')
      setFieldModalVisible(false)
      setEditingWideTable(null)
      fieldForm.resetFields()
    } catch (error) {
      message.error('字段配置保存失败')
    }
  }

  // 表格列定义
  const columns: ColumnsType<WideTable> = [
    {
      title: '宽表名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true
    },
    {
      title: '显示名称',
      dataIndex: 'displayName',
      key: 'displayName',
      width: 150,
      ellipsis: true
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type: string) => (
        <Tag color={type === 'ONLINE' ? 'blue' : 'green'}>
          {type === 'ONLINE' ? '在线' : '离线'}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string, record: WideTable) => (
        <Switch
          checked={status === 'ACTIVE'}
          onChange={(checked) => handleStatusChange(record.id, checked ? 'ACTIVE' : 'INACTIVE')}
          checkedChildren="激活"
          unCheckedChildren="停用"
        />
      )
    },
    {
      title: '数据总数',
      dataIndex: 'dataCount',
      key: 'dataCount',
      width: 100,
      render: (count: number) => count ? count.toLocaleString() : '-'
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 100,
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: WideTable) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => {
                // 查看详情逻辑
                console.log('查看详情:', record)
              }}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="字段管理">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={() => handleManageFields(record)}
            />
          </Tooltip>
          {record.type === 'ONLINE' && (
            <Tooltip title="同步到ES">
              <Button
                type="text"
                icon={<SyncOutlined />}
                onClick={() => handleSync(record.id)}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确认删除？"
            description="删除后不可恢复，请谨慎操作"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ]

  useEffect(() => {
    fetchWideTableList()
    fetchStatistics()
  }, [])

  return (
    <div>
      {/* 页面头部 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1>数据宽表管理</h1>
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingWideTable(null)
              createForm.resetFields()
              setCreateModalVisible(true)
            }}
          >
            创建数据宽表
          </Button>
          <Button
            icon={<CloudUploadOutlined />}
            onClick={() => navigate('/wide-table/import')}
          >
            Excel导入
          </Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="总数" value={statistics.total} prefix={<TableOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="在线宽表" value={statistics.online} valueStyle={{ color: '#1890ff' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="离线宽表" value={statistics.offline} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="已激活" value={statistics.active} valueStyle={{ color: '#f5222d' }} />
          </Card>
        </Col>
      </Row>

      {/* 查询表单 */}
      <Card style={{ marginBottom: 24 }}>
        <Form
          form={queryForm}
          layout="inline"
          onFinish={(values) => fetchWideTableList({ current: 1, ...values })}
        >
          <Form.Item name="name" label="宽表名称">
            <Input placeholder="请输入宽表名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="类型">
            <Select placeholder="请选择类型" allowClear style={{ width: 120 }}>
              <Option value="ONLINE">在线</Option>
              <Option value="OFFLINE">离线</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              <Option value="ACTIVE">激活</Option>
              <Option value="INACTIVE">停用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button
                onClick={() => {
                  queryForm.resetFields()
                  fetchWideTableList({ current: 1 })
                }}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table<WideTable>
          columns={columns}
          dataSource={wideTableList}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setPagination({ ...pagination, current: page, pageSize: size })
              fetchWideTableList({ current: page, size })
            }
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={editingWideTable ? '编辑数据宽表' : '创建数据宽表'}
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false)
          setEditingWideTable(null)
          createForm.resetFields()
        }}
        onOk={() => createForm.submit()}
        width={600}
        destroyOnClose
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreateOrUpdate}
        >
          <Form.Item
            name="name"
            label="宽表名称"
            rules={[{ required: true, message: '请输入宽表名称' }]}
          >
            <Input placeholder="请输入宽表名称" />
          </Form.Item>
          <Form.Item
            name="displayName"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <TextArea rows={3} placeholder="请输入描述" />
          </Form.Item>
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select placeholder="请选择类型">
              <Option value="ONLINE">在线</Option>
              <Option value="OFFLINE">离线</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dataSource" label="数据源配置">
            <TextArea rows={3} placeholder="请输入数据源配置" />
          </Form.Item>
          <Form.Item name="esIndexName" label="ES索引名称">
            <Input placeholder="自动生成或手动输入" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 字段管理模态框 */}
      <Modal
        title={`字段管理 - ${editingWideTable?.displayName}`}
        open={fieldModalVisible}
        onCancel={() => {
          setFieldModalVisible(false)
          setEditingWideTable(null)
          fieldForm.resetFields()
        }}
        onOk={() => fieldForm.submit()}
        width={1000}
        destroyOnClose
      >
        <Form
          form={fieldForm}
          onFinish={handleSaveFields}
        >
          <Form.List name="fields">
            {(fields, { add, remove }) => (
              <div>
                <div style={{ marginBottom: 16 }}>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加字段
                  </Button>
                </div>
                {fields.map(({ key, name, ...restField }) => (
                  <Card key={key} size="small" style={{ marginBottom: 8 }}>
                    <Row gutter={16}>
                      <Col span={6}>
                        <Form.Item
                          {...restField}
                          name={[name, 'fieldName']}
                          label="字段名称"
                          rules={[{ required: true, message: '请输入字段名称' }]}
                        >
                          <Input placeholder="字段名称" />
                        </Form.Item>
                      </Col>
                      <Col span={6}>
                        <Form.Item
                          {...restField}
                          name={[name, 'displayName']}
                          label="显示名称"
                          rules={[{ required: true, message: '请输入显示名称' }]}
                        >
                          <Input placeholder="显示名称" />
                        </Form.Item>
                      </Col>
                      <Col span={4}>
                        <Form.Item
                          {...restField}
                          name={[name, 'fieldType']}
                          label="类型"
                          rules={[{ required: true, message: '请选择类型' }]}
                        >
                          <Select placeholder="类型">
                            <Option value="STRING">字符串</Option>
                            <Option value="NUMBER">数值</Option>
                            <Option value="DATE">日期</Option>
                            <Option value="BOOLEAN">布尔</Option>
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={3}>
                        <Form.Item
                          {...restField}
                          name={[name, 'isDisplayField']}
                          label="显示字段"
                          valuePropName="checked"
                        >
                          <Switch size="small" />
                        </Form.Item>
                      </Col>
                      <Col span={3}>
                        <Form.Item
                          {...restField}
                          name={[name, 'isQueryField']}
                          label="查询字段"
                          valuePropName="checked"
                        >
                          <Switch size="small" />
                        </Form.Item>
                      </Col>
                      <Col span={2}>
                        <div style={{ paddingTop: 30 }}>
                          <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => remove(name)}
                          />
                        </div>
                      </Col>
                    </Row>
                  </Card>
                ))}
              </div>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  )
}

export default WideTableManagement